package com.mall.b2c.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.domain.delivery.DeliveryMethodDomain;
import com.mall.b2c.service.DeliveryMethodService;
import com.mall.b2c.util.JsonDataGridHelper;
import com.mall.common.bean.Pager;
import com.mall.common.bean.SearchFilter;
import com.mall.common.controller.BaseController;
import com.mall.common.domain.AreaDomain;
import com.mall.common.exception.NoticeException;
import com.mall.common.hibernate.Finder;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.IntRangeFieldValidator;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;
import com.mall.common.web.Servlets;

/**
 * 配送方式
 * @author lzx
 *
 */
@Controller
@RequestMapping("/admin/b2c/deliveryMethod")
public class DeliveryMethodController extends BaseController{
	@Resource private DeliveryMethodService deliveryMethodService;
	
	/**
	 * 跳转到列表页面
	 */
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list(Model model){
		return "/admin/b2c/deliveryMethod/list";
	}

	/**
	 * 获取列表信息
	 */
	@RequestMapping(value="/queryData", method=RequestMethod.POST)
	@ResponseBody
	public Pager queryData(Pager pager, HttpServletRequest request){
    	Map<String, Object> filterParams = Servlets.getParametersStartingWith(request);
		List<SearchFilter> filters = SearchFilter.parse(filterParams);
    	pager = deliveryMethodService.findPage(pager, filters);
		return JsonDataGridHelper.createJSONData(pager);
    }
	
    /**
	 * 跳转到新增页面
	 */
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String input(){
		return "/admin/b2c/deliveryMethod/input";
	}
	
	/**
	 * 保存
	 */
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "name", message = "配送方式名称不允许为空!")
		},
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "priority", message = "排序不允许为空!")
		},
		intRangeFields = {
			@IntRangeFieldValidator(fieldName = "priority", min = "0", message = "排序必须为零或正整数!")
		}
	)
	@RequestMapping(value="/save", method=RequestMethod.POST)
	public String save(DeliveryMethodDomain deliveryMethod, String[] area, String[] display, BigDecimal[] fw, 
			BigDecimal[] fp, BigDecimal[] cw, BigDecimal[] cp, Model model, HttpServletResponse response){
		if(!deliveryMethodService.isUnique("name", null, deliveryMethod.getName())) {
			throw new NoticeException("该配送方式名称已存在");
		}
		deliveryMethod.setConfig(assembly(area, display, fw, fp, cw, cp));
		deliveryMethodService.persist(deliveryMethod);
		return ResponseUtils.renderJSON(successMessage, response);
    }
    
	/**
	 * 编辑
	 */
	@Validations(
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "id", message = "ID非法!")
		}
	)
	@RequestMapping(value="/edit", method=RequestMethod.GET)
	public String edit(Long id, Model model){
		DeliveryMethodDomain deliveryMethod = deliveryMethodService.find(id);
    	model.addAttribute("deliveryMethod", deliveryMethod);
		return "/admin/b2c/deliveryMethod/input";
	}
	
	/**
	 * 修改
	 */
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "name", message = "配送方式名称不允许为空!")
		},
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "priority", message = "排序不允许为空!")
		},
		intRangeFields = {
			@IntRangeFieldValidator(fieldName = "priority", min = "0", message = "排序必须为零或正整数!")
		}
	)
	@RequestMapping(value="/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(DeliveryMethodDomain deliveryMethod, String[] area, String[] display, BigDecimal[] fw, 
			BigDecimal[] fp, BigDecimal[] cw, BigDecimal[] cp, HttpServletResponse response){
		DeliveryMethodDomain currentDeliveryMethod = deliveryMethodService.find(deliveryMethod.getId());
		if(currentDeliveryMethod == null) {
			throw new NoticeException("当前配送方式不存在!");
		}
		if(!deliveryMethodService.isUnique("name", currentDeliveryMethod.getName(), deliveryMethod.getName())) {
			throw new NoticeException("配送方式已存在!");
		}

		deliveryMethod.setConfig(assembly(area, display, fw, fp, cw, cp));
		deliveryMethodService.updateByUpdater(deliveryMethod);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
	private String assembly(String[] areas, String[] displays, BigDecimal[] fws, 
			BigDecimal[] fps, BigDecimal[] cws, BigDecimal[] cps){
		if(areas == null){
			return null;
		}
		if(displays == null || displays.length != areas.length){
			throw new NoticeException("区域配置有误");
		}
		if(fws == null || fws.length != areas.length){
			throw new NoticeException("区域首重配置有误");
		}
		if(fps == null || fps.length != areas.length){
			throw new NoticeException("区域首重价格配置有误");
		}
		if(cws == null || cws.length != areas.length){
			throw new NoticeException("区域续重配置有误");
		}
		if(cps == null || cps.length != areas.length){
			throw new NoticeException("区域续重价格配置有误");
		}
		JSONObject config = new JSONObject();
		for(int i = 0;i < areas.length;i++){
			JSONObject areaConfig = new JSONObject();
			areaConfig.put("display", displays[i]);
			areaConfig.put("firstWeight", fws[i]);
			areaConfig.put("firstPrice", fps[i]);
			areaConfig.put("continueWeight", cws[i]);
			areaConfig.put("continuePrice", cps[i]);
			config.put(areas[i], areaConfig);
		}
		return config.toString();
	}

	@RequestMapping(value="/areaTree", method=RequestMethod.POST)
	@ResponseBody
	public List<AreaDomain> areaTree(){
		Finder finder = Finder.create("from AreaDomain bean where bean.parent is null");
		return finder.findHQLList();
	}
	
    /**
	 * 删除
	 */
	@Validations(
		requiredFields = {
			@RequiredFieldValidator(fieldName = "ids", message = "ids非法")	
		}
	)
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(Long[] ids, HttpServletResponse response){
		deliveryMethodService.remove(ids);
    	return ResponseUtils.renderJSON(successMessage, response);
    }
	
	/**
	 * 名称是否已存在
	 */
	@RequestMapping("/checkName")
	@ResponseBody
	public Boolean checkBrandName(String oldName, @RequestParam("name") String newName) {
		return deliveryMethodService.isUnique("name", oldName, newName);
	}

	/**
	 * 切换默认配送方式
	 */
	@Validations(
			requiredStrings = {
					@RequiredStringValidator(fieldName = "id", message = "ID为空!")
			}
	)
	@RequestMapping("/default")
	@ResponseBody
	public String switchDefault(Long id, HttpServletResponse response) {
		deliveryMethodService.switchDefault(id);
		return ResponseUtils.renderJSON(successMessage, response);
	}
	
}
